﻿$(function () {
    $(".nodes").sortable({
        connectWith: ".nodes",
        placeholder: "ph ui-state-highlight",
        update: fUpdate
    }).disableSelection();

    $(".nodes .add").click(fAdd);

    $(".nodes .edit").click(fEdit);

    $(".nodes .delete").click(fDelete);

    $(".nodes .showhide").click(fShowHide);

    $("#cancel").click(function () {
        hideModal($("#editbox"));
    });

    $("#submit").click(function () {
        Submit();
    });

    $("#editbox").keypress(function (event) {
        if (event.which == '13') {
            Submit();
        }
    });

    $("#create").click(function () {

        var parentnodeid = "1";
        var displayorder = $("#p_1").children().length + 1;

        addNode(parentnodeid, displayorder);
    });

    $("#Title").autocomplete({
        source: "/Pages/GetPagesBySearch",
        minLength: 0,
        focus: function (event, ui) {
            $("#Title").val(ui.item.Title);
            $("#Url").val(ui.item.Url);
            return false;
        },
        select: function (event, ui) {
            $("#Title").val(ui.item.Title);
            $("#Url").val(ui.item.Url);
            return false;
        }
    }).data("autocomplete")._renderItem = function (ul, item) {
        return $("<li></li>")
				.data("item.autocomplete", item)
				.append("<a>" + item.Title + " (" + item.Url + ")</a>")
				.appendTo(ul);
    };

});

function fUpdate (event, ui) {

    if (ui.sender == null) {

        var parentnodeid = ui.item.parent().attr("id").split("_")[1];

        var nodes = [];
        ui.item.parent().children('li').each(function (idx, elm) {
            nodes.push({
                ID: elm.id.split('_')[1],
                DisplayOrder: idx + 1
            });
        });

        var input = {
            ParentNodeID: parentnodeid,
            Nodes: nodes
        };

        Ajax({
            url: "/SiteMap/MobileUpdate",
            data: JSON.stringify(input),
            success: function (data) {
                if (data.success) {
                    ShowMessage("saved");
                }
            }
        });

        //db("update " + ui.item.parent().attr("id"));
    }
}

function fShowHide() {

    var nodeid = $(this).parent().attr("id").split("_")[1];
    $("#p_" + nodeid).toggle();
    var src = $("#p_" + nodeid).is(":visible") ? "/Content/images/tree_minus.png" : "/Content/images/tree_plus.png";
    $("img", $(this)).attr("src", src);
}

function fAdd () {

    var parentnodeid = $(this).parent().attr("id").split("_")[1];
    var displayorder = $(this).parent().parent().children().length + 1;

    addNode(parentnodeid, displayorder);
}

function fEdit () {
    var nodeid = $(this).parent().attr("id").split("_")[1];

    var input = {
        NodeID: nodeid
    };

    Ajax({
        url: "/SiteMap/MobileGetNode",
        data: JSON.stringify(input),
        success: function (data) {
            $("#NodeID").val(data.Node.ID);
            $("#ParentNodeID").val("");
            $("#DisplayOrder").val(""),
                $("#Title").val(data.Node.Title);
            $("#Url").val(data.Node.Url);
            showModal($("#editbox"));
        }
    });
}

function fDelete () {

    if (!confirm("are you sure?")) {
        return;
    }

    var nodeid = $(this).parent().attr("id").split("_")[1];

    var input = {
        NodeID: nodeid
    };

    Ajax({
        url: "/SiteMap/MobileDeleteNode",
        data: JSON.stringify(input),
        success: function (data) {
            $("#n_" + input.NodeID).fadeOut(1000, function () {
                $(this).remove();
                if ($("#n_" + input.NodeID).parent().children().length == 0) {
                    $("#n_" + input.NodeID).parent().hide();
                }
            });

            ShowMessage("deleted");
        }
    });
}

function addNode(parentnodeid, displayorder) {
    $("#NodeID").val("0");
    $("#ParentNodeID").val(parentnodeid);
    $("#DisplayOrder").val(displayorder);
    $("#Title").val("");
    $("#Url").val("");
    showModal($("#editbox"));
}

function db(message) {
    $("#msg").html($("#msg").html() + "<br/>" + message);
}

function Submit() {

    $("#submit").hide();

    var input = {
        ID: $("#NodeID").val(),
        ParentNodeID: $("#ParentNodeID").val(),
        DisplayOrder: $("#DisplayOrder").val(),
        Title: $("#Title").val(),
        Url: $("#Url").val()
    };

    Ajax({
        url: "/Sitemap/MobileSaveNode",
        data: JSON.stringify(input),
        success: function (data) {
            ShowValidationErrors(data);
            if (data.IsSaved == true) {
                hideModal($("#editbox"));
                ShowMessage("saved");

                if (input.ParentNodeID.length > 0) {
                    var liclass;
                    if (input.ParentNodeID == "1") {
                        liclass = "level1";
                    } else {
                        liclass = "level2";
                    }

                    var html = "<li id=\"n_" + data.ID + "\" class=\"" + liclass + "\"><span>" + input.Title + "</span>";
                    html += "<a href=\"#\"class=\"delete\"><img src=\"/Content/images/cross.png\" alt=\"delete\" /></a>";
                    html += "<a href=\"#\" class=\"edit\"><img src=\"/Content/images/pencil.png\" alt=\"Edit\" /></a>";
                    html += "<a href=\"#\" class=\"add\"><img src=\"/Content/images/add.png\" alt=\"Add\" /></a>";
                    html += "<ul id=\"p_" + data.ID + "\" class=\"nodes\"></ul></li>";

                    $("#p_" + input.ParentNodeID).show().append(html);

                    $("#p_" + data.ID).sortable({
                        connectWith: ".nodes",
                        placeholder: "ph ui-state-highlight",
                        update: fUpdate
                    }).disableSelection();

                    $("#n_" + data.ID + " .add").click(fAdd);
                    $("#n_" + data.ID + " .edit").click(fEdit);
                    $("#n_" + data.ID + " .delete").click(fDelete);
                    $("#n_" + data.ID + " .showhide").click(fShowHide);
                }

                $("#n_" + input.ID + " span:first").text(input.Title);
                $("#n_" + input.ID + " span:first").fadeOut(1000, function () {
                    $(this).fadeIn(2000)
                });
            }
        },
        complete: function () {
            $("#submit").show();
        }
    });
}

